import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
import router from '@/router'

// 创建axios实例
const instance = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 10000, // 10秒超时
  withCredentials: true // 允许跨域携带凭证
})

// 不需要token的白名单路径
const whiteList = [
  '/user/register',
  '/user/login'
]

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    console.log('Request config:', config)
    const tokenStore = useTokenStore()
    
    // 检查是否是白名单请求
    const isWhitelisted = whiteList.some(path => {
      const isMatch = config.url === path || config.url.startsWith(path + '?')
      console.log(`Checking path ${config.url} against whitelist ${path}: ${isMatch}`)
      return isMatch
    })
    
    // 非白名单请求且存在token时添加Authorization头
    if (tokenStore.token && !isWhitelisted) {
      console.log('Adding authorization token to request')
      config.headers.Authorization = `Bearer ${tokenStore.token}`
    } else if (!isWhitelisted) {
      console.warn('No token available for non-whitelisted request')
    }
    
    return config
  },
  (err) => {
    console.error('Request interceptor error:', err)
    return Promise.reject(err)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    console.log('Response received:', response)
    
    // 处理业务状态码
    if (response.data.code === 0) {
      console.log('Request successful')
      return response.data
    }
    
    // 业务错误处理
    const errorMsg = response.data.msg || '服务异常'
    console.error('Business error:', errorMsg)
    ElMessage.error(errorMsg)
    return Promise.reject(response.data)
  },
  (err) => {
    console.error('Response error:', err)
    
    // 网络错误处理
    if (err.response) {
      switch (err.response.status) {
        case 401:
          // 避免循环重定向
          if (!window.location.pathname.includes('/login')) {
            console.log('Redirecting to login due to 401')
            ElMessage.error('登录已过期，请重新登录')
            router.push('/login')
          }
          break
        case 403:
          ElMessage.error('无权限访问')
          break
        case 404:
          ElMessage.error('请求资源不存在')
          break
        case 500:
          ElMessage.error('服务器错误')
          break
        default:
          ElMessage.error(`服务异常 (${err.response.status})`)
      }
    } else if (err.message.includes('timeout')) {
      ElMessage.error('请求超时，请检查网络连接')
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    
    return Promise.reject(err)
  }
)

export default instance